import React, { useState, useEffect, useRef, useCallback } from "react";
import { Button, Table, Space, Form, Input, Popconfirm, Tag, Select } from "antd";
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  SearchOutlined,
  SyncOutlined,
  DownOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import TableLayout, {
  SearchContainer,
  SearchAction,
  SearchForm,
  OperateContainer,
  MainContainer,
} from "@/components/templates/TableLayout";
import { ButtonCollapsed } from "@/components/iteration";
import { EditorModel } from "@/pages/system/menu/components";
import { IconComponent } from "@/components/custom";
import { AuthButton } from "@/components/auth";
import PropTypes from "prop-types";
import { getTreeMenuList, addMenu, updateMenu, deleteMenu } from "@/api/system/menu";

const AUTH_PERMISSION = {
  ADD: "system:menu:add",
  UPDATE: "system:menu:update",
  DELETE: "system:menu:delete",
  SYNC: "system:menu:update:sync",
};

const HeaderComponent = ({ onSearch, onReset }) => {
  const [folded, setFolded] = useState(false);
  const [searchType, setSearchType] = useState("keyword");
  const inputRef = useRef(null);

  const onFinish = (values) => {
    const data = Object.entries(values).filter(([_, value]) => !!value);
    data.length && onSearch(Object.fromEntries(data));
  };

  const hanldeSearch = () => {
    const value = inputRef.current.input.value;
    value && onSearch({ [searchType]: value });
  };

  const options = [
    { label: "综合搜索", value: "keyword", placeholder: "综合搜索" },
    { label: "菜单名称", value: "menuName", placeholder: "请输入菜单名称" },
  ];

  return (
    <SearchContainer>
      <SearchAction>
        <Space.Compact>
          <Select
            defaultValue={searchType}
            style={{ width: 120 }}
            options={options}
            onChange={(v) => setSearchType(v)}
          />
          <Input ref={inputRef} placeholder={options.find((item) => item.value === searchType).placeholder} />
          <Button icon={<SearchOutlined />} onClick={hanldeSearch} />
        </Space.Compact>

        <ButtonCollapsed
          type="link"
          icon={<DownOutlined />}
          iconPosition="end"
          collapsed={folded}
          onClick={() => setFolded(!folded)}
        >
          高级搜索
        </ButtonCollapsed>
      </SearchAction>
      <SearchForm collapse={folded}>
        <Form className="search-card" layout="inline" autoComplete="off" onFinish={onFinish} onReset={onReset}>
          <Form.Item name="menuName" label="菜单名称">
            <Input placeholder="请输入菜单名称" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                搜索
              </Button>
              <Button icon={<SyncOutlined />} htmlType="reset">
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </SearchForm>
    </SearchContainer>
  );
};
HeaderComponent.propTypes = {
  onSearch: PropTypes.func,
  onReset: PropTypes.func,
};
const OperateCompoent = ({ onInsert, onRefresh }) => {
  return (
    <OperateContainer>
      <Space>
        <AuthButton auth={AUTH_PERMISSION.ADD} type="primary" ghost icon={<PlusOutlined />} onClick={onInsert}>
          添加
        </AuthButton>
      </Space>
      <Space>
        <Button icon={<ReloadOutlined />} onClick={onRefresh} />
      </Space>
    </OperateContainer>
  );
};
OperateCompoent.propTypes = {
  onInsert: PropTypes.func,
  onRefresh: PropTypes.func,
};

const TableComponent = ({ onEditor, onDelete, onChangeStatus, ...resProps }) => {
  const columns = [
    { key: "menuName", title: "菜单名称", dataIndex: "menuName" },
    {
      key: "menuIcon",
      title: "图标",
      dataIndex: "menuIcon",
      with: "40px",
      render: (value) => <IconComponent value={value} />,
    },
    { key: "orderNum", title: "排序", dataIndex: "orderNum" },
    { key: "menuPath", title: "路由地址", dataIndex: "menuPath" },
    { key: "menuCode", title: "权限标识", dataIndex: "menuCode" },
    { key: "component", title: "组件路径", dataIndex: "component" },
    {
      key: "statusName",
      title: "状态",
      dataIndex: "statusName",
      render: (value, { status }) => <Tag color={status ? "#909399" : "#108ee9"}>{value}</Tag>,
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space>
          {/* <EditorModelComponent
            initialValues={{
              parentId: record.menuId,
              orderNum: record.children ? [...record.children].pop().orderNum + 1 : 1,
            }}
            callback={onAdd}
          >
            <AuthButton auth={AUTH_PERMISSION.ADD} type="link" icon={<PlusOutlined />}>
              添加
            </AuthButton>
          </EditorModelComponent> */}

          <AuthButton
            auth={AUTH_PERMISSION.UPDATE}
            type="link"
            icon={<EditOutlined />}
            onClick={() => onEditor(record)}
          >
            编辑
          </AuthButton>

          <Popconfirm
            title="系统提示"
            description={`是否确认删除ID为${record.menuId}的数据项？`}
            onConfirm={() => onDelete(record.menuId)}
            okText="是"
            cancelText="否"
          >
            <AuthButton auth={AUTH_PERMISSION.DELETE} type="link" danger icon={<DeleteOutlined />}>
              删除
            </AuthButton>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <MainContainer>
      <Table size="middle" {...resProps} columns={columns} />
    </MainContainer>
  );
};
TableComponent.propTypes = {
  onEditor: PropTypes.func,
  onDelete: PropTypes.func,
  onChangeStatus: PropTypes.func,
  resProps: PropTypes.object,
};

const GeneralComponent = () => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [editorVisible, setEditorVisible] = useState(false);
  const [editorData, setEditorData] = useState({});

  const onGetData = useCallback((options = {}) => {
    setLoading(true);
    getTreeMenuList(options)
      .then((res) => setDataSource(res))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    onGetData();
  }, [onGetData]);

  const onSearch = (values) => {
    onGetData(values);
  };

  const onAddData = async (values) => {
    await addMenu(values);
    onGetData();
  };

  const onEditorData = async (values) => {
    await updateMenu(values);
    onGetData();
  };

  const onDelete = async (value) => {
    await deleteMenu(value);
    onGetData();
  };

  const onCancelModel = () => {
    Object.entries(editorData).length && setEditorData({});
    setEditorVisible(false);
  };

  return (
    <TableLayout>
      <EditorModel
        open={editorVisible}
        initialValues={editorData}
        onCallback={editorData.userId ? onEditorData : onAddData}
        onCancel={onCancelModel}
      />
      <HeaderComponent onSearch={onSearch} />
      <OperateCompoent
        onInsert={() => setEditorVisible(true)}
        onRefresh={() => onGetData()}
        onReset={() => onGetData()}
      />
      <TableComponent
        dataSource={dataSource}
        loading={loading}
        pagination={false}
        onEditor={(v) => {
          setEditorData(v);
          setEditorVisible(true);
        }}
        onDelete={onDelete}
      />
    </TableLayout>
  );
};

export default GeneralComponent;
